package com.hod.client.reserves;

import java.util.Date;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ListBox;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Record;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.DateField;
import com.gwtext.client.widgets.form.FieldSet;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.NumberField;
import com.gwtext.client.widgets.form.TextField;
import com.hod.client.HOD;
import com.hod.client.backend.orm.client.GearsDataObject;
import com.hod.client.backend.orm.client.GearsDataStore;
import com.hod.client.bed.Bed;
import com.hod.client.bed.BedRecordset;
import com.hod.client.client.Client;
import com.hod.client.client.ClientRecordset;
import com.hod.client.frontend.HODForm;
import com.hod.client.room.Room;
import com.hod.client.room.RoomRecordset;
import com.hod.client.roomtype.RoomType;
import com.hod.client.roomtype.RoomTypeRecordset;

public class ReservationFormPanel extends HODForm {
	
	
	protected final TextField txtIdReservation = new TextField("idReservation", "idReservation", 150);
    protected final TextField txtcodeReservation = new TextField("codeReservation", "codeReservation", 150);
    protected final DateField txtDate = new DateField("dateReservation", "dateReservation", 150);
    protected final DateField txtExpiration = new DateField("expiration", "expiration", 150);
    protected final NumberField txtBeck = new NumberField("beck", "beck", 150);
    protected final NumberField txtPaxCount = new NumberField("paxCount", "paxCount", 150);
    protected final NumberField txtDayCount = new NumberField("dayCount", "dayCount", 150);
    protected final ListBox txtIdRoomType = new ListBox();
    protected final ListBox txtIdReservationState = new ListBox();
    protected final ListBox txtIdClient = new ListBox();
    protected final ListBox txtIdRoom = new ListBox();
    protected final ListBox txtIdBed = new ListBox();
    private Integer idClient = 0;
    
    
    public ReservationFormPanel(GearsDataStore ds) {
		super(ds);
		add(createFieldSet());        
        createButtons();
	}
	
    

    
	public void setIdClient(Integer idClient){
		this.idClient = idClient;
	}
    
    public void updateDataControls(Record record){
    	for (int i=0;i<txtIdRoomType.getItemCount();i++)
            if (Integer.valueOf(txtIdRoomType.getValue(i))==record.getAsInteger("idRoomType"))
      	       txtIdRoomType.setItemSelected(i, true);
         
         for (int i=0;i<txtIdReservationState.getItemCount();i++)
             if (Integer.valueOf(txtIdReservationState.getValue(i))==record.getAsInteger("idReservationState"))
             	txtIdReservationState.setItemSelected(i, true);
         
         for (int i=0;i<txtIdClient.getItemCount();i++)
             if (Integer.valueOf(txtIdClient.getValue(i))==record.getAsInteger("idClient"))
             	txtIdClient.setItemSelected(i, true);
         
         for (int i=0;i<txtIdRoom.getItemCount();i++)
             if (Integer.valueOf(txtIdRoom.getValue(i))==record.getAsInteger("idRoom"))
             	txtIdRoom.setItemSelected(i, true);
         
         for (int i=0;i<txtIdRoom.getItemCount();i++)
             if (Integer.valueOf(txtIdBed.getValue(i))==record.getAsInteger("idBed"))
             	txtIdBed.setItemSelected(i, true);
    }
    
	protected FieldSet createFieldSet() {
		// TODO Auto-generated method stub
		for(Room r: RoomRecordset.getRooms()){            	
        	txtIdRoom.addItem(r.getNumber(),String.valueOf(r.getIdRoom()));
        }
		
		for(Bed r: BedRecordset.getBed()){            	
        	txtIdBed.addItem(r.getIdBed()+"",String.valueOf(r.getIdBed()));
        }
		
		for(RoomType rt: RoomTypeRecordset.getRoomTypes()){            	
        	txtIdRoomType.addItem(rt.getName(),String.valueOf(rt.getIdRoomType()));
        }
                
        for(ReservationState rs: ReservationRecordset.getReservationStates()){
        	txtIdReservationState.addItem(rs.getName(),String.valueOf(rs.getIdReservationState()));
        }
                
        //txtIdClient = client.createClientCombo();
        for(Client c: ClientRecordset.getClients()){
        	   txtIdClient.addItem(c.getName(),String.valueOf(c.getIdClient()));
        	   if ((idClient!=0) && (idClient.equals(c.getIdClient()))){
        		   txtIdClient.setItemSelected(txtIdClient.getItemCount()-1, true);
        	   }
        }
		//txtIdRoomType.setEnabled(occupationEnabled());
        
		FieldSet fieldSet = new FieldSet();
        fieldSet.setLabelWidth(80);
        fieldSet.setTitle("Reservation Details");
        fieldSet.setAutoHeight(true);
        fieldSet.setBorder(false);

        //the field names must match the data field values from the Store
        fieldSet.add(txtIdReservation);
        fieldSet.add(txtcodeReservation);
        fieldSet.add(txtDate);
        fieldSet.add(txtExpiration);
        fieldSet.add(txtBeck);
        fieldSet.add(txtPaxCount);
        fieldSet.add(txtDayCount);
        fieldSet.add(new Label("Tipo de habitacion"));
        fieldSet.add(txtIdRoomType);
        fieldSet.add(new HTML("<BR/>"));
        fieldSet.add(new Label("Estado"));
        fieldSet.add(txtIdReservationState);
        fieldSet.add(new HTML("<BR/>"));
        fieldSet.add(new Label("Cliente"));
        fieldSet.add(txtIdClient);
        fieldSet.add(new HTML("<BR/>"));
        fieldSet.add(new Label("Habitacion"));
        fieldSet.add(txtIdRoom);
        fieldSet.add(new HTML("<BR/>"));
        fieldSet.add(new Label("Cama"));
        fieldSet.add(txtIdBed);
        fieldSet.add(new HTML("<BR/>"));
        
        txtcodeReservation.setAllowBlank(true);
        txtDate.setAllowBlank(false);
        txtExpiration.setAllowBlank(false);
        txtBeck.setAllowBlank(true);
        txtPaxCount.setAllowBlank(false);
        txtDayCount.setAllowBlank(false);
        
        
        txtIdReservation.setReadOnly(true);
        txtIdReservation.setVisible(false);
        txtIdReservation.setHideLabel(true);
        
        txtPaxCount.setAllowDecimals(false);
        txtPaxCount.setAllowNegative(false);
        txtDayCount.setAllowDecimals(false);
        txtDayCount.setAllowNegative(false);
        txtBeck.setAllowDecimals(true);
        txtBeck.setAllowNegative(false);
        
        txtDate.setValue(new Date());
        txtDayCount.setValue(1);
        
        
        return fieldSet;
	}
	
	protected void createButtons() {
		// TODO Auto-generated method stub
		
        ButtonListenerAdapter savelistener = new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	try {
            		Reservation o = null;
            		if (txtIdReservation.getText()==""){
            			o = new Reservation();
            			o.setIdReservation(null);
            		}else{
            			o = (Reservation) ds.findById(Integer.valueOf(txtIdReservation.getText()));
            		}
                    o.setCodeReservation(txtcodeReservation.getText());
                    o.setDateReservation(txtDate.getValue());
                    o.setExpiration(txtExpiration.getValue());
                    o.setBeck(Double.valueOf(txtBeck.getText()));
                    o.setPaxCount(Integer.valueOf(txtPaxCount.getText()));
                    o.setDayCount(Integer.valueOf(txtDayCount.getText()));                        
                    o.setIdRoomType(Integer.valueOf(txtIdRoomType.getValue(txtIdRoomType.getSelectedIndex())));
                    o.setIdReservationState(Integer.valueOf(txtIdRoomType.getValue(txtIdReservationState.getSelectedIndex())));                
                    o.setIdClient(Integer.valueOf(txtIdClient.getValue(txtIdClient.getSelectedIndex())));
                    o.setIdRoom(Integer.valueOf(txtIdRoom.getValue(txtIdRoom.getSelectedIndex())));
                    o.setIdBed(Integer.valueOf(txtIdBed.getValue(txtIdBed.getSelectedIndex())));
                    //decremento el numero de habitacion para ese tipo de habitacion
                    if (RoomTypeRecordset.decreaseRoomTypeCapacity(o.getIdRoomType())){
                    	ds.save(o);
                    	HOD.reload();
                    }else
                    	Window.alert("No fue posible actualizar la cantidad de habitaciones disponibles. Verifique disponibilidad");                    
				} 
            	catch (Exception e1) {
					// TODO Auto-generated catch block
					Window.alert(e1.getMessage());
				}
            }
        };
        ButtonListenerAdapter deletelistener = new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	try {
            		ds.delete((Reservation) ds.findById(new Integer(txtIdReservation.getText())));
            		HOD.reload();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					Window.alert(e1.getMessage());
				}
            }
        };
        ButtonListenerAdapter createlistener = new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	try {
            		getForm().reset();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					Window.alert(e1.getMessage());
				}
            }
        };
        	           
        
        Button save = new Button("Save", savelistener);
        Button delete = new Button("Delete", deletelistener);
		Button newRecord = new Button("New", createlistener);
        Button cancel = new Button("Cancel");

        addButton(save);
        addButton(delete);
        addButton(cancel);
        addButton(newRecord);
		
	}




	@Override
	public void setObject(GearsDataObject object) {
		Reservation r = (Reservation) object;
		txtcodeReservation.setValue(r.getCodeReservation());
		txtDate.setValue(r.getDateReservation());
		txtExpiration.setValue(r.getExpiration());
		txtBeck.setValue(r.getBeck());
		txtPaxCount.setValue(r.getPaxCount());
		txtDayCount.setValue(r.getDayCount());
		
		for (int i=0;i<txtIdRoomType.getItemCount();i++)
            if (Integer.valueOf(txtIdRoomType.getValue(i))==r.getIdRoomType())
      	       txtIdRoomType.setItemSelected(i, true);
         
         for (int i=0;i<txtIdReservationState.getItemCount();i++)
             if (Integer.valueOf(txtIdReservationState.getValue(i))==r.getIdReservationState())
             	txtIdReservationState.setItemSelected(i, true);
         
         for (int i=0;i<txtIdClient.getItemCount();i++)
             if (Integer.valueOf(txtIdClient.getValue(i))==r.getIdClient())
             	txtIdClient.setItemSelected(i, true);
         
         for (int i=0;i<txtIdRoom.getItemCount();i++)
             if (Integer.valueOf(txtIdRoom.getValue(i))==r.getIdRoom())
             	txtIdRoom.setItemSelected(i, true);
         
         for (int i=0;i<txtIdBed.getItemCount();i++)
             if (Integer.valueOf(txtIdBed.getValue(i))==r.getIdBed())
             	txtIdBed.setItemSelected(i, true);
                               	
	}


}
